package com.ruoyi.projects.apis;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.IgnoreAuth;
import com.ruoyi.common.annotation.LoginUserInfo;
import com.ruoyi.common.constant.BuConstants;
import com.ruoyi.common.core.controller.ApiBaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.projects.Vos.WxUserInfoDTO;
import com.ruoyi.projects.domain.SlCustom;
import com.ruoyi.projects.service.ISlCustomService;
import com.ruoyi.projects.service.IWxAuthTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 会员相关接口
 */
@RestController
@RequestMapping("/api/customers")
public class CustomerApis extends ApiBaseController {

    @Autowired
    private IWxAuthTokenService wxAuthTokenService;

    @Autowired
    private ISlCustomService slCustomService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 会员微信授权登录
     */
    @PostMapping("/codeExOpenid")
    @IgnoreAuth
    public ApiResult codeExOpenid(@RequestBody WxUserInfoDTO dto) {
        try {
            String openid = null;
            WxUserInfoDTO miniCodeSession = null;
            if (dto.getCode().equals("1234")) {
                //接口模拟登录
                openid = "oLjuT7T3IKscSZkuJI4JQmkoID30";
                miniCodeSession = new WxUserInfoDTO();
                miniCodeSession.setOpenid(openid);
            } else {
                //小程序授权登录
                miniCodeSession = wxAuthTokenService.getMiniCodeSession(dto.getCode());
                if (StringUtils.isNotEmpty(miniCodeSession.getOpenid())) {
                    openid = miniCodeSession.getOpenid();
                } else {
                    //code换取openid失败
                    return ApiResult.error(miniCodeSession.getErrmsg());
                }
            }
            SlCustom slCustom = slCustomService.selectSlCustomByOpenId(openid);
            if (slCustom == null) {
                //新用户
            } else {
                //老用户
                miniCodeSession.setId(slCustom.getId());
                miniCodeSession.setNickName(slCustom.getNickname());
                miniCodeSession.setOpenid(slCustom.getOpenId());
                miniCodeSession.setAvatarUrl(slCustom.getAvatarurl());
                miniCodeSession.setGender(Integer.parseInt(slCustom.getGender()));
                miniCodeSession.setPhone(slCustom.getPhone());
                miniCodeSession.setIntegral(slCustom.getIntegral());
            }
            // 生成token
            String token = UUID.randomUUID().toString();
            miniCodeSession.setToken(token);
            // 保存token到Redis，设置过期时间
            redisCache.setCacheObject(BuConstants.MINITOKEN + token, miniCodeSession, 7, TimeUnit.DAYS);
            return ApiResult.success(miniCodeSession);
        } catch (Exception e) {
            return ApiResult.error(e.getMessage());
        }
    }

    /**
     * 微信授权登录保存用户信息
     *
     * @param dto
     * @param userInfo
     * @return
     */
    @PostMapping("/saveUserInfo")
    public ApiResult saveUserInfo(@LoginUserInfo WxUserInfoDTO dto, @RequestBody WxUserInfoDTO userInfo) {
        try {
            WxUserInfoDTO wxUserInfoDTO = slCustomService.saveWxUserInfo(dto, userInfo);
            return ApiResult.success(wxUserInfoDTO);
        } catch (Exception e) {
            return ApiResult.error("保存用户信息失败");
        }
    }

    /**
     * 解析获取微信用户手机号接口
     * @return
     */
    @PostMapping("/getPhone")
    public ApiResult getPhone(@RequestBody WxUserInfoDTO dto) {
        // 1. 通过 code 从微信服务器获取手机号
        ApiResult userPhoneResult = wxAuthTokenService.getUserPhoneNumber(dto.getCode());
        if (ApiResult.EnumCode.SUCCESS.getCode()==userPhoneResult.getCode()){
            JSONObject data = (JSONObject) userPhoneResult.getData();
            SlCustom slCustom = slCustomService.selectSlCustomByOpenId(dto.getOpenid());
            if (slCustom==null){
                //用户不存在
            }else {
                // 2. 更新用户手机号
                JSONObject phone_info = (JSONObject)data.get("phone_info");
                slCustom.setPhone(phone_info.get("purePhoneNumber").toString());
                slCustomService.updateSlCustom(slCustom);
            }
            return ApiResult.success("获取成功",slCustom.getPhone());
        }else {
            //获取手机号失败
            return ApiResult.error("获取手机号失败");
        }
    }



}
